#ifndef RGA_UTIL_H
#define RGA_UTIL_H

#include "im2d.h"
#include "rga.h"
#include "rknn_engine.h"

/**
 * @brief Context for the RGA hardware accelerator.
 *
 * Holds resources for RGA, including the handle and tensor memory
 * for the NPU input buffer. This buffer is shared between RGA and RKNN.
 */
typedef struct
{
    rga_buffer_handle_t npu_input_handle; // RGA handle for the NPU input buffer
    rknn_tensor_mem *npu_input_mem;       // RKNN tensor memory for the NPU input buffer

} rga_context_t;

/**
 * @brief Initializes the RGA context and creates a shared buffer for NPU input.
 * @param rga_ctx Pointer to the RGA context to initialize.
 * @param rknn_ctx Pointer to the initialized RKNN engine context.
 * @return 0 on success, -1 on failure.
 */
int rga_init(rga_context_t *rga_ctx, rknn_engine_context_t *rknn_ctx);

/**
 * @brief Deinitializes the RGA context and releases associated resources.
 * @param rga_ctx Pointer to the RGA context to deinitialize.
 * @param rknn_ctx Pointer to the RKNN engine context.
 */
void rga_deinit(rga_context_t *rga_ctx, rknn_engine_context_t *rknn_ctx);

/**
 * @brief Uses RGA to preprocess a single video frame.
 *
 * Performs hardware-accelerated letterbox resizing and color space conversion
 * (e.g., NV12 to RGB) on a source frame, writing the result to the NPU input buffer.
 *
 * @param rga_ctx Pointer to the initialized RGA context.
 * @param src_dma_fd DMA-BUF file descriptor of the source frame (from V4L2).
 * @param src_width Width of the source frame.
 * @param src_height Height of the source frame.
 * @param src_format V4L2 pixel format of the source frame.
 * @return 0 on success, -1 on failure.
 */
int rga_preprocess_frame(rga_context_t *rga_ctx, int src_dma_fd, int src_width, int src_height, int src_format);

/**
 * @brief Uses RGA to draw detection results onto a display buffer.
 * @param display_dma_fd DMA-BUF file descriptor of the buffer to be displayed.
 * @param frame_width Width of the display frame.
 * @param frame_height Height of the display frame.
 * @param results Pointer to the detection results to be drawn.
 * @return 0 on success, -1 on failure.
 */
int rga_draw_results(int display_dma_fd, int frame_width, int frame_height, detect_result_group_t *results);

#endif // RGA_UTIL_H
